#include "soft_timer.h"

static LIST_HEAD(list_timers);

/**
 * @brief  初始化一个软件定时器
 */
void TimerInit(Timer_t *timer, uint32_t uMesc, E_TimerMode eMode, TimerProc timerProc, void *arg)
{
    param_assert(timer != NULL);

    timer->uMesc      = uMesc;
    timer->fTimerProc = timerProc;
    timer->arg        = arg;
    timer->bStop      = true;
    timer->eMode      = eMode;
    List_Add(&list_timers, &timer->node);  // 将创建的定时器 插入链表
}

/**
 * @brief  启动软件定时器
 */
void TimerStart(Timer_t *timer)
{
    param_assert(timer != NULL);
    timer->bStop    = false;
    timer->uCurTick = timer->uMesc;
}

/**
 * @brief  暂停软件定时器
 */
void TimerStop(Timer_t *timer)
{
    param_assert(timer != NULL);
    timer->bStop = true;
}

/**
 * @brief  恢复软件定时器
 */
void TimerResume(Timer_t *timer)
{
    param_assert(timer != NULL);
    timer->bStop = false;
}

/**
 * @brief  复位软件定时器
 */
void TimerReset(Timer_t *timer)
{
    param_assert(timer != NULL);
    timer->uCurTick = timer->uMesc;
}

/**
 * @brief  软件定时器设置周期
 */
void TimerSetPeriod(Timer_t *timer, uint32_t uMesc)
{
    param_assert(timer != NULL);
    timer->uMesc = uMesc;
}

/**
 * @brief  软件定时器设置回调函数
 */
void TimerSetProc(Timer_t *timer, TimerProc proc, void *arg)
{
    param_assert(timer != NULL);
    timer->fTimerProc = proc;
    timer->arg        = arg;
}

/**
 * @brief  软件定时器后台处理函数
 */
void TimerMsHander(void)
{
    ListNode_t *pNode;
    Timer_t *timer = NULL;

    list_foreach_front(&list_timers, pNode)
    {
        timer = list_entry(pNode, Timer_t, ListNode_t);
        if (timer == NULL || timer->bStop == true) {
            continue;
        }
        if (timer->uCurTick != 0) {
            timer->uCurTick--;
        } else {
            if (timer->eMode == TIMER_MODE_ONE_SHOT) {
                timer->bStop = true;
            }
            timer->uCurTick = timer->uMesc;
            timer->fTimerProc(timer->arg);
        }
    }
}
